﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
namespace DeskNote
{
    static internal class InterceptMouse
    {
        internal delegate void MouseClickHandler();
        internal static event MouseClickHandler MouseClicked;
        private static LowLevelMouseProc _proc = HookCallback;
        private static IntPtr _hookID = IntPtr.Zero;
        static Point _mousePos = new Point(0, 0);
        internal static Point MousePos
        {
            get
            {
                return _mousePos;
            }
        }

       

        private const int WH_MOUSE_LL = 14;
        private enum MouseMessages
        {
            WM_LBUTTONDOWN = 0x0201,
            WM_LBUTTONUP = 0x0202,
            WM_MOUSEMOVE = 0x0200,
            WM_MOUSEWHEEL = 0x020A,
            WM_RBUTTONDOWN = 0x0204,
            WM_RBUTTONUP = 0x0205
        }
        [StructLayout(LayoutKind.Sequential)]
        private struct POINT
        {
            internal int x;
            internal int y;
        }
        [StructLayout(LayoutKind.Sequential)]
        private struct MSLLHOOKSTRUCT
        {
            internal POINT pt;
            internal uint mouseData;
            internal uint flags;
            internal uint time;
            internal IntPtr dwExtraInfo;
        }
        internal static void HookMouse()
        {
            _hookID = SetHook(_proc);
        }
        internal static void UnHookMouse()
        {
            if (_hookID != IntPtr.Zero)
                NativeMethods.UnhookWindowsHookEx(_hookID);
        }
        private static IntPtr SetHook(LowLevelMouseProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return NativeMethods.SetWindowsHookEx(WH_MOUSE_LL, proc,
                    NativeMethods.GetModuleHandle(curModule.ModuleName), 0);
            }
        }
        internal delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);
        private static IntPtr HookCallback(
        int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 &&
                MouseMessages.WM_LBUTTONDOWN == (MouseMessages)wParam)
            {
                MSLLHOOKSTRUCT hookStruct = (MSLLHOOKSTRUCT)Marshal.PtrToStructure(lParam, typeof(MSLLHOOKSTRUCT));
                //Console.WriteLine(hookStruct.pt.x + ", " + hookStruct.pt.y);
                _mousePos = new Point(hookStruct.pt.x, hookStruct.pt.y);
                MouseClicked();
            } return NativeMethods.CallNextHookEx(_hookID, nCode, wParam, lParam);
        }
    }
}